import wtforms
from wtforms.validators import Email,length,EqualTo,InputRequired
from models import UserModel,EmailCaptcha

#验证前端提交数据是否符号要求
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="请输入正确的邮箱格式")])
    captcha = wtforms.StringField(validators=[length(4,4,message="请输入正确的验证码")])
    username = wtforms.StringField(validators=[length(2,20,message="请输入正确的用户名")])
    password = wtforms.StringField(validators=[length(6,20,message="密码格式错误")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password",message="两次密码不一致")])

    #自定义验证：邮箱是否已注册，验证码是否正确
    def validate_email(self,field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError("邮箱已注册")

    def validate_captcha(self,field):
        cpatcha = field.data
        email = self.email.data
        cap = EmailCaptcha.query.filter_by(email=email,captcha=cpatcha).first()
        if not cap:
            raise wtforms.ValidationError("邮箱或验证码错误")
        #删除数据库内已验证的验证码

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="请输入正确的邮箱格式")])
    password = wtforms.StringField(validators=[length(6,20,message="密码格式错误")])

class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[length(1,100,message="标题长度为1-100")])
    content = wtforms.StringField(validators=[length(1,message="内容长度不为空")])

class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[length(1,message="内容长度不为空")])
    question_id = wtforms.IntegerField(validators=[InputRequired(message="问题id不能为空")])